package skeleton;

import java.io.IOException;

import util.Config;
import util.Lib;
import util.Pair;

public class Player {
	private byte color;
	ChessInfo info = new ChessInfo();
	Board board;
	GBoard gboard;
	Solution s = null;
	static final boolean GUI = Config.getBoolean("GUI");
	static final boolean PAUSE = Config.getBoolean("PAUSE");
	
	static final int LEN = 15;
	static final byte EMPTY = '*';
	
	
	public Player() {
		board = new Board();
		if (GUI) {
			gboard = new GBoard();
			gboard.father = this;
		}
		String solutionName = Config.getString("Solution");
		try {
			s = (Solution) Class.forName(solutionName).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void setColor(byte c) {color = c;}
	public byte getColor() {return color;}
	
	public ChessInfo putChess() {
		showBoard();
		info.color = color;
		int solveResult = s.solve(board, info);
		println("solve result : " + solveResult);
		println("nodes = : " + heuristic.HeuristicSolution.nodes);
		if (solveResult == Solution.WIN) {
			if (GUI) gboard.setGameover();
			return info;
		}
		if (solveResult == Solution.LOST) {
			if (GUI) gboard.setGameover();
			return info;
		}
		board.data[info.row][info.col] = color;
		Lib.assertTrue(info.color == color);
		println("choose position: " + (info.row+0) + " " + (info.col+0));
		if (GUI) gboard.setChess(info.row, info.col);
		if (PAUSE && Startup.mode == 0)
			try {
				System.in.read();
			} catch (IOException e) {
				e.printStackTrace();
			}
		return info;
	}

	public void updateBoard(ChessInfo newInfo) {
		if (Startup.mode == 0) 
			if (GUI) gboard.setChess(newInfo.row, newInfo.col);
		info.row = newInfo.row;
		info.col = newInfo.col;
		board.data[newInfo.row][newInfo.col] = newInfo.color;
	}
	
	public void println(Object o) {
		System.out.println(o);
	}
	public void print(Object o) {
		System.out.print(o);
	}
	
	public void showBoard() {
		println("------------------------the original board-------------------------------");
		for (int i=0; i<LEN; ++i){
			for (int j=0; j<LEN; ++j)
				if (board.data[i][j] == EMPTY) print((char)EMPTY);
				else print((board.data[i][j]+0));
			print("\n");
		}
	}

	public void chessed() {
		Lib.assertTrue(GUI);
		Pair pos = gboard.getLastPos();
		ChessInfo info = new ChessInfo();
		info.row = (byte) pos.first;
		info.col = (byte) pos.second;
		info.color = (byte) ((color == 0) ? 1 : 0);
		updateBoard(info);
		putChess();
	}
}
